package com.hubu.web;

import com.hubu.mapper.administratorUserMapper;
import com.hubu.mapper.teacherUserMapper;
import com.hubu.pojo.administratorUser;
import com.hubu.pojo.studentUser;
import com.hubu.mapper.studentUserMapper;
import com.hubu.pojo.teacherUser;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        //1. 接收用户名、密码和角色
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = request.getParameter("role");

        //2. 选择并调用正确的MyBatis方法
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        studentUser studentuser = null;
        teacherUser teacheruser = null;
        administratorUser administratoruser = null;

        try {
            if ("student".equals(role)) {
                studentUserMapper studentMapper = sqlSession.getMapper(studentUserMapper.class);
                studentuser = studentMapper.select(username, password);

            } else if ("teacher".equals(role)) {
                teacherUserMapper teacherMapper = sqlSession.getMapper(teacherUserMapper.class);
                teacheruser = teacherMapper.select(username, password);
            } else if ("admin".equals(role)) {
                administratorUserMapper adminMapper = sqlSession.getMapper(administratorUserMapper.class);
                administratoruser = adminMapper.select(username, password);
            } else {
                writer.write("未知角色类型");
                return;
            }
        } finally {
            sqlSession.close();
        }

        //3. 根据角色进行验证和重定向
        if(studentuser != null||teacheruser != null||administratoruser != null) { // 登录成功
            String param1 = request.getParameter("username");
            //这里简单只加一个参数
           // String param2 = "value2";
           // String redirectUrl = "http://example.com/destination?param1=" + URLEncoder.encode(param1, "UTF-8") + "&param2=" + URLEncoder.encode(param2, "UTF-8");
            switch(role) {
                case "student":
                    Cookie cookie11 =new Cookie("username",username);
                    Cookie cookie12 =new Cookie("password",password);
                    response.addCookie(cookie11);
                    response.addCookie(cookie12);
                    response.sendRedirect(request.getContextPath() + "/studentHome");
                    break;
                case "teacher":
                    response.sendRedirect(request.getContextPath() + "/teacherHome?username="+ URLEncoder.encode(param1, "UTF-8"));
                    break;
                case "admin":
                    response.sendRedirect(request.getContextPath() + "/adminHome");
                    break;
            }
        } else {

            writer.println("<script type='text/javascript'>");
            writer.println("alert('登录失败，请检查用户名和密码是否正确！');");
            writer.println("window.location='" + request.getContextPath() + "/login.html';");
            writer.println("</script>");
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }



//    构建不定长url参数的方法
//    private String buildRedirectUrl(String baseUrl, String... queryParams) {
//        StringBuilder urlBuilder = new StringBuilder(baseUrl);
//        if (queryParams.length > 0) {
//            urlBuilder.append("?");
//            for (String param : queryParams) {
//                urlBuilder.append(param).append("&");
//            }
//            urlBuilder.deleteCharAt(urlBuilder.length() - 1); // Remove the extra "&" at the end
//        }
//        return urlBuilder.toString();
//    }
}


